package com.itheima.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.itheima.canal.config.RabbitmqConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;


@CanalEventListener//声明一个监听类
public class SpuListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * spu 表更新 商品上架
     * @param eventType 对数据库库表操作类型
     * @param rowData 当前操作数据库的数据
     */

    //括号内依次为（数据库，表，操作类型）
    @ListenPoint(schema = "changgou_goods",table = "tb_spu",eventType = CanalEntry.EventType.UPDATE)
    public void goods_up(CanalEntry.EventType eventType,CanalEntry.RowData rowData){

        Map<String,String> oldMap = new HashMap<>();
        for (CanalEntry.Column column : rowData.getBeforeColumnsList()) {
            oldMap.put(column.getName(),column.getValue());
        }

        Map<String,String> newMap = new HashMap<>();
        rowData.getAfterColumnsList().forEach((c)->newMap.put(c.getName(),c.getValue()));

        if("0".equals(oldMap.get("is_marketable")) && "1".equals(newMap.get("is_marketable"))){
            //上架状态由0 -> 1 说明是新上架的商品
            String spuId = newMap.get("id");
            //根据spuId把该商品上传至索引库
            rabbitTemplate.convertAndSend(RabbitmqConfig.GOODS_UP_EXCHANGE,"",spuId);
        }

        if("1".equals(oldMap.get("is_marketable")) && "0".equals(newMap.get("is_marketable"))){
            String spuId = newMap.get("id");
            rabbitTemplate.convertAndSend(RabbitmqConfig.GOODS_DOWN_EXCHANGE,"",spuId);
        }


    }





















//    @ListenPoint(schema = "changgou_goods", table = {"tb_spu"},eventType = CanalEntry.EventType.UPDATE )
//    public void goodsUp(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
//        System.out.println("tb_spu表数据发生变化");
//
//        //修改前数据
//        Map<String ,String> oldMap=new HashMap<>();
//        for(CanalEntry.Column column: rowData.getBeforeColumnsList()) {
//            oldMap.put(column.getName(),column.getValue());
//        }
//
//        //修改后数据
//        Map<String,String> newMap=new HashMap<>();
////        for(CanalEntry.Column column: rowData.getAfterColumnsList()) {
////            newMap.put(column.getName(),column.getValue());
////        }
//        rowData.getAfterColumnsList().forEach((c)->newMap.put(c.getName(),c.getValue()));
//
//        //is_marketable  由0改为1表示上架 获取最新上架的商品
//        if("0".equals(oldMap.get("is_marketable")) && "1".equals(newMap.get("is_marketable")) ){
//            //发送到mq商品上架交换器上
//            rabbitTemplate.convertAndSend(RabbitmqConfig.GOODS_UP_EXCHANGE,"",newMap.get("id"));
//        }
//    }
}
